﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace OverStore.Runtime.ObjectRepository.CallbackManager
{
    /// <summary>
    /// Composes few instances implements <see cref="ICallbackManager{TInstance}"/> interface.
    /// </summary>
    /// <typeparam name="TInstance">The type of the instance.</typeparam>
    public class CompositeCallbackManager<TInstance> : ICallbackManager<TInstance>
        where TInstance : class
    {
        private readonly IEnumerable<ICallbackManager<TInstance>> _CallbackManagers;

        /// <summary>
        /// Initializes a new instance of the <see cref="CompositeCallbackManager&lt;TInstance&gt;"/> class.
        /// </summary>
        /// <param name="callbackManagers">The callback managers.</param>
        public CompositeCallbackManager(IEnumerable<ICallbackManager<TInstance>> callbackManagers)
        {
            if (Object.ReferenceEquals(callbackManagers, null))
                throw new ArgumentNullException("callbackManagers");
            _CallbackManagers = callbackManagers;
        }

        /// <summary>
        /// Performs operations as response to specified action.
        /// If method returns <c>false</c>, the operation which provides callback must be interrupted.
        /// Some operation can't be interrupted.
        /// </summary>
        /// <param name="instance">The instance been argument of persistence operation.</param>
        /// <param name="operation">The persistence operation performed on instance.</param>
        /// <returns>
        /// 	<c>true</c> to continue persistence operation, <c>false</c> to stop persistence operation.
        /// </returns>
        /// <exception cref="PersistingRuntimeException">Error occured due callback processing.</exception>
        public bool Callback(TInstance instance, PersistenceOperation operation)
        {
            return _CallbackManagers.Aggregate(true, (r, c) => c.Callback(instance, operation) && r);
        }
    }
}
